<template>
  <div class="chat-container">
    <h1>简易聊天室</h1>
    <div v-if="!isConnected" class="alert alert-warning">正在尝试连接服务器...</div>
    <div v-if="isConnected" class="messages">
      <div v-for="message in messages" :key="message.id" class="message">
        <strong>{{ message.username }}:</strong> {{ message.text }}
      </div>
    </div>
    <div v-if="isConnected">
      <input v-model="message" @keyup.enter="sendMessage" placeholder="请输入消息..." />
    </div>
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted } from "vue";
import io from "socket.io-client";

export default {
  name: "Chat",
  setup() {
    const socket = ref(null);
    const messages = ref([]);
    const message = ref("");
    const isConnected = ref(false);
    let heartbeatTimer = null;

    // 初始化 WebSocket 连接
    const connectSocket = () => {
      socket.value = io("http://localhost:3000");

      // 连接成功
      socket.value.on("connect", () => {
        isConnected.value = true;
        console.log("连接成功");
        startHeartbeat();
      });

      // 接收到消息
      socket.value.on("message", (msg) => {
        messages.value.push(msg);
      });

      // 监听连接断开
      socket.value.on("disconnect", () => {
        isConnected.value = false;
        console.log("连接断开，尝试重新连接...");
        stopHeartbeat();
        reconnectSocket();
      });

      // 监听连接错误
      socket.value.on("connect_error", (err) => {
        console.log("连接错误:", err);
      });
    };

    // 发送消息
    const sendMessage = () => {
      if (message.value.trim()) {
        socket.value.emit("message", {
          username: "User",
          text: message.value,
          id: Date.now(),
        });
        message.value = ""; // 清空输入框
      }
    };

    // 心跳检测，定时发送 ping 消息
    const startHeartbeat = () => {
      heartbeatTimer = setInterval(() => {
        if (socket.value.connected) {
          socket.value.emit("ping");
        }
      }, 30000); // 每30秒发送一次心跳
    };

    // 停止心跳
    const stopHeartbeat = () => {
      if (heartbeatTimer) {
        clearInterval(heartbeatTimer);
        heartbeatTimer = null;
      }
    };

    // 重新连接
    const reconnectSocket = () => {
      setTimeout(() => {
        console.log("正在重新连接...");
        connectSocket();
      }, 3000); // 每3秒重新连接一次
    };

    // 在组件挂载时连接 WebSocket
    onMounted(() => {
      connectSocket();
    });

    // 在组件卸载时清理连接
    onUnmounted(() => {
      if (socket.value) {
        socket.value.disconnect();
        stopHeartbeat();
      }
    });

    return {
      socket,
      messages,
      message,
      isConnected,
      sendMessage,
    };
  },
};
</script>

<style scoped>
.chat-container {
  width: 400px;
  margin: 0 auto;
  padding: 20px;
  border: 1px solid #ccc;
  background-color: #f9f9f9;
}
.messages {
  margin-bottom: 10px;
  max-height: 300px;
  overflow-y: auto;
}
.message {
  margin: 5px 0;
}
input {
  width: 100%;
  padding: 8px;
  margin-top: 10px;
}
.alert {
  background-color: yellow;
  padding: 5px;
  text-align: center;
}
</style>